package cn.workreport.ws.handler;

import cn.workreport.ws.util.WsSessionManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.AbstractWebSocketHandler;

import java.time.LocalDateTime;

@Slf4j
@Component
public class MyWsHandler extends AbstractWebSocketHandler {


    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        log.info("建立ws连接 ===>" + session.getId());
        // 放入 session
        WsSessionManager.add(session.getId(), session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        log.info("ws发送文本消息");
        // 获取客户端传来的消息
        String payload = message.getPayload();
        log.info("server 接受到消息：" + payload);
        session.sendMessage(
                new TextMessage("server 发送给的消息 【" + payload + "】，发送时间：" + LocalDateTime.now().toString())
        );
    }

    @Override
    protected void handleBinaryMessage(WebSocketSession session, BinaryMessage message) throws Exception {
        super.handleBinaryMessage(session, message);
        log.info("ws发送二进制消息");
    }

    @Override
    protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception {
        super.handlePongMessage(session, message);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
        log.info("ws异常处理");
        // 清除 session 并关闭连接
        WsSessionManager.removeAndClose(session.getId());
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        log.info("关闭ws连接 ===>" + session.getId());
        // 清除 session 并关闭连接
        WsSessionManager.removeAndClose(session.getId());
    }
}
